package com.dyc.course.biz.controller;

import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dyc.course.biz.entity.Course;
import com.dyc.course.biz.repository.CourseRepository;
import com.dyc.course.common.utils.R;
import com.dyc.course.sys.entity.SysDeptEntity;

@RestController
@RequestMapping("/biz/course")
public class CourseController {

	@Autowired
	private CourseRepository repository;

	@RequestMapping(value = "/list")
	public R list(@RequestParam Map<String, Object> params) {
		String page = (String) params.get("page");
		String size = (String) params.getOrDefault("limit", "10");
		String sortBy = (String) params.getOrDefault("sortBy", "id");
		Sort sort = Sort.by(sortBy);
		PageRequest pageRequest = PageRequest.of(Integer.parseInt(page)-1, Integer.parseInt(size), sort);
		Page<Course> entities;
		if (params.containsKey("name") && params.get("name").toString().length() > 0) {
			entities = repository.findByNameLike("%" + (String) params.get("name") + "%", pageRequest);
		} else {
			entities = repository.findAll(pageRequest);
		}
		return R.ok().put("page", entities);
	}

	@RequestMapping("/info/{id}")
	public R info(@PathVariable("id") Long id) {
		Optional<Course> optional = repository.findById(id);
		Course entity = null;
		if (optional.isPresent()) {
			entity = optional.get();
		}
		return R.ok().put("info", entity);
	}
	
	@RequestMapping("/save")
	public R save(@RequestBody Course entity) {
		if (entity.getDeptId() != null) {
			SysDeptEntity dept = new SysDeptEntity();
			dept.setDeptId(entity.getDeptId());
			entity.setDept(dept);
		}
		repository.save(entity);
		return R.ok();
	}

	@RequestMapping("/delete")
	public R delete(long id){
		repository.deleteById(id);
		return R.ok();
	}
	
}
